#!/usr/bin/env python

import errno, os, sys

if __name__ == '__main__':
    sys.path.append(
            os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))

import maitch
import mcommon

import libhdvbd.mscript

from maitch import opj

__already_run = False

def init(ctx):
    global __already_run
    if __already_run:
        return
    __already_run = True
    if ctx.mode == 'configure':
        pass
    elif ctx.mode == 'build':

        gst_bases = ['tune']

        my_builddir = opj(ctx.build_dir, "tools")
        ctx.ensure_out_dir(my_builddir)

        # gudev flags/libs include gobject's
        cflags = "${CFLAGS} ${SQLITE_CFLAGS} ${GUDEV_CFLAGS} " + \
                mcommon.hdvbd_includes
        gst_cflags = cflags + " ${GSTREAMER_CFLAGS}"
        libs = "${LIBS} ${SQLITE_LIBS} ${GUDEV_LIBS} -Llibhdvbd -lhdvbd"
        gst_libs = libs + " ${GSTREAMER_LIBS} -lhdvbd-gst"
        deps = "libhdvbd/libhdvbd.la"
        gst_deps = "libhdvbd/libhdvbd.la libhdvbd/libhdvbd-gst.la"

        c_files = ctx.glob_src("*.c", "tools", False)
        o_files = maitch.change_suffix_with_prefix(c_files, ".c", ".lo",
                "tool-")
        bases = maitch.change_suffix(c_files, ".c", "")

        for x in bases:
            if os.path.basename(x) in gst_bases:
                # Note use of wdeps: have to force libraries to be built before
                # tools' .c -> .o to generate headers from gobs
                ctx.add_rule(maitch.LibtoolCRule(
                        sources = x + ".c",
                        cflags = gst_cflags,
                        prefix = "gst-tool-",
                        wdeps = gst_deps,
                        quiet = True))
            else:
                ctx.add_rule(maitch.LibtoolCRule(
                        sources = x + ".c",
                        cflags = cflags,
                        prefix = "tool-",
                        wdeps = deps,
                        quiet = True))

        for x in bases:
            if os.path.basename(x) in gst_bases:
                f = gst_cflags
                l = gst_libs
                d = gst_deps
                p = "gst-tool-"
            else:
                f = cflags
                l = libs
                d = deps
                p = "tool-"
            ctx.add_rule(maitch.LibtoolCProgramRule(
                    sources = maitch.add_prefix(x + ".lo", p),
                    targets = maitch.add_prefix(x, "hdvb-"),
                    deps = d,
                    cflags = f,
                    libs = l,
                    libtool_mode_arg = '-shared',
                    quiet = True))



if __name__ == '__main__':
    ctx = mcommon.init(PACKAGE = "hdvb",
            BUILD_DIR = os.path.abspath(opj(os.path.dirname(sys.argv[0]),
                    os.pardir, "build")))
    libhdvbd.mscript.init(ctx)
    init(ctx)
    ctx.run()

